const express = require('express');
const uuid = require('node-uuid');
const { Message,MessageList } = require('../utils/message');
const achievementModel = require('../models/achievement');

const router = express.Router();

router.post('/',(req,res,next)=>{
  const {employeeId,name,employeeType,baseWage,rating,remark,time} = req.body;
  const id = uuid.v1();
  const ratingTime=new Date(time);
  const year=ratingTime.getFullYear();
  const month=ratingTime.getMonth()+1;
  const achievement = new achievementModel({id,employeeId,name,employeeType,baseWage,rating,remark,year,month});
  achievement.save().then(data=>{
    if(data){
      res.json(Message(200,'添加成功！'));
    }
  });
});

router.delete('/',(req,res,next)=>{
  const {id}=req.query;
  if(id){
    achievementModel.deleteOne({id}).then(data=>{
      if(data.deletedCount!==0){
        res.json(Message(200,'删除成功！'))
      }else{
        res.json(Message(400,'删除失败'))
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'))
  }
})

router.put('/',(req,res,next)=>{
  const {id}=req.query;
  const {rating,reamrk}=req.body;
  if(id){
    achievementModel.updateOne({id},{rating,reamrk}).then(data=>{
      if(data.acknowledged&&data.modifiedCount!==0){
        res.json(Message(200,'修改成功！'));
      }else{
        res.json(Message(400,'修改失败！'));
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'));
  }
})

router.get('/',(req,res,next)=>{
  const {id,name,year,month}=req.query;
  let {page=1,pageSize=10}=req.query;
  let regexp=new RegExp(name,'i');
  const queryObj={};
  if(id){
    achievementModel.findOne({id}).then(data=>{
      if(data){
        res.json(Message(200,'',data))
      }else{
        res.json(Message(400,'未查询到相关数据'))
      }
    })
  }
  if(name) queryObj.$or=[{name:{$regex:regexp}}];
  if(year) queryObj.year=year;
  if(month) queryObj.month=month;
  achievementModel.find(queryObj).count((err,count)=>{
    achievementModel.find(queryObj)
      .limit(pageSize)
      .skip((page-1)*pageSize)
      .then(data=>{
        res.json(MessageList(200,'',data,page,pageSize,count));
    })
  })
})
module.exports = router